<template>
    <n-spin :show="loading">
        <n-space vertical :size="12">
            <n-space justify="space-between">
                <n-space>
                    <n-button type="warning" @click="doExport">导出提现数据</n-button>
                    <n-button type="info" :disabled="srows.length == 0" @click="doBatchTran">提交转账</n-button>
                    <n-button type="success" :disabled="srows.length == 0" @click="doBatchFinish">标记完成</n-button>
                    <n-button type="error" :disabled="srows.length == 0" @click="doBatchAbort">标记中止</n-button>
                </n-space>
                <n-space>
                    <n-form inline :model="param" :show-label="false" :show-feedback="false" ref="formRef">
                        <n-form-item>
                            <n-input v-model:value="param.query.mob" style="width: 160px" clearable placeholder="手机号" />
                        </n-form-item>
                        <n-form-item>
                            <n-select
                                v-model:value="param.query.state"
                                clearable
                                style="width: 120px"
                                placeholder="提现状态"
                                :options="[
                                    { label: '所有状态', value: 0 },
                                    { label: '等待处理', value: 1 },
                                    { label: '提现成功', value: 2 },
                                    { label: '提交转账', value: 3 },
                                    { label: '转账失败', value: 4 },
                                    { label: '提现中止', value: 9 },
                                ]"
                            />
                        </n-form-item>
                        <n-form-item>
                            <n-select
                                v-model:value="param.query.cnl"
                                clearable
                                style="width: 120px"
                                placeholder="提现渠道"
                                :options="[
                                    { label: '所有渠道', value: 0 },
                                    { label: '微信提现', value: 2 },
                                    { label: '支付宝提现', value: 3 },
                                    { label: '银行卡提现', value: 1 },
                                ]"
                            />
                        </n-form-item>
                        <n-form-item>
                            <n-tooltip trigger="hover">
                                <template #trigger>
                                    <n-date-picker v-model:value="dates" style="width: 250px" type="daterange" :update-value-on-close="true" />
                                </template>
                                申请时间段
                            </n-tooltip>
                        </n-form-item>
                    </n-form>

                    <n-button @click="doQuery">
                        <template #icon>
                            <n-icon :component="YoutubeSearchedForRound" />
                        </template>
                        查询
                    </n-button>
                </n-space>
            </n-space>
            <n-data-table
                striped
                size="large"
                type="selection"
                :checked-row-keys="srows"
                :max-height="height"
                :min-height="items.length > 0 ? height : 0"
                :row-key="(row:any) => row.id"
                @update:checked-row-keys="onCheckRow"
                :columns="columns"
                :data="items"
            />
            <n-space justify="end">
                <n-pagination show-size-picker :page="param.pager.page" :page-size="param.pager.size" :page-count="pager.all" :page-sizes="[10, 25, 50, 100]" @update:page="onChangePage" @update:page-size="onChangeSize">
                    <template #prefix="{}">当前 {{ pager.now }} / {{ pager.all }} 页，共 {{ pager.row }} 条数据</template>
                </n-pagination>
            </n-space>
        </n-space>
        <Finish :items="datas" v-model:show="finishActive" v-if="finishActive" @refresh="execLoad"></Finish>
        <Abort :items="datas" v-model:show="abortActive" v-if="abortActive" @refresh="execLoad"></Abort>
        <Tran :items="datas" v-model:show="tranActive" v-if="tranActive" @refresh="execLoad"></Tran>
    </n-spin>
</template>

<script lang="ts" setup>
import { h, ref, computed, onActivated, watch } from 'vue'
import { NSpace, NText, NIcon, NButton, NTooltip, NTag } from 'naive-ui'
import { YoutubeSearchedForRound, CheckCircleOutlineOutlined } from '@vicons/material'
import { TransactionOutlined, StopOutlined } from '@vicons/antd'

import { useStore } from '@/store'
import { Http } from '@/libs'

import Finish from './Finish.vue'
import Abort from './Abort.vue'
import Tran from './Tran.vue'

import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn' // 导入本地化语言
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.locale('zh-cn')
dayjs.extend(customParseFormat)

const store = useStore()

const loading = computed(() => store.state.loading.flag)

const columns = [
    {
        type: 'selection',
        fixed: 'left',
        align: 'center',
    },
    {
        title: '提现用户',
        key: 'apply',
        width: 300,
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []

            if (row.apply.type == 2) {
                comps[comps.length] = h(NTag, { bordered: false, size: 'small', type: 'info' }, { default: () => '门店' })
            } else {
                comps[comps.length] = h(NTag, { bordered: false, size: 'small', type: 'warning' }, { default: () => '会员' })
            }

            comps[comps.length] = h(NText, { type: 'success' }, { default: () => '[ ' + row.apply.mob + ' ]' })

            comps[comps.length] = h(NText, {}, { default: () => row.apply.name })

            return h(NSpace, {}, { default: () => comps })
        },
    },

    {
        title: '收款人',
        key: 'payee',
        align: 'left',
        width: 150,
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            if (row.cnl == 2) {
                comps[comps.length] = h(NTag, { size: 'small', type: 'info' }, { default: () => '微　信' })
            } else if (row.cnl == 3) {
                comps[comps.length] = h(NTag, { size: 'small', type: 'success' }, { default: () => '支付宝' })
            } else if (row.cnl == 1) {
                comps[comps.length] = h(NTag, { size: 'small', type: 'warning' }, { default: () => '银行卡' })
            }
            comps[comps.length] = h(
                NTooltip,
                {},
                {
                    default: () => {
                        if (row.cnl == 2) {
                            return '账户绑定微信'
                        } else if (row.cnl == 3) {
                            return row.payee.key
                        } else if (row.cnl == 1) {
                            return row.payee.bank + ' / ' + row.payee.card
                        }
                        return '未知'
                    },
                    trigger: () => h(NText, {}, { default: () => row.payee.name }),
                }
            )

            return h(NSpace, {}, { default: () => comps })
        },
    },
    {
        title: '状态',
        key: 'state',
        align: 'center',
        width: 100,
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []

            if (row.state == 1) {
                comps[comps.length] = h(NButton, { size: 'tiny', type: 'default' }, { default: () => '等待处理' })
            } else if (row.state == 2) {
                comps[comps.length] = h(NButton, { size: 'tiny', type: 'success' }, { default: () => '提现完成' })
            } else if (row.state == 3) {
                comps[comps.length] = h(NButton, { size: 'tiny', type: 'info' }, { default: () => '提交转账' })
            } else if (row.state == 4) {
                comps[comps.length] = h(NButton, { size: 'tiny', type: 'warning' }, { default: () => '转账失败' })
            } else if (row.state == 9) {
                comps[comps.length] = h(NButton, { size: 'tiny', type: 'error' }, { default: () => '提现中止' })
            }

            return h(NSpace, {}, { default: () => comps })
        },
    },
    {
        title: '金额',
        key: 'value',
        align: 'right',
        width: 100,
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            return (row.value / 100).toFixed(2)
        },
    },
    {
        title: '进度',
        key: 'time',
        align: 'left',
        width: 270,
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            if (row.time) {
                comps[comps.length] = h(NSpace, {}, { default: () => [h(NText, { type: 'default' }, { default: () => '发起申请' }), h(NText, {}, { default: () => row.time })] })
            }
            if (row.tran.time) {
                comps[comps.length] = h(NSpace, {}, { default: () => [h(NText, { type: 'info' }, { default: () => '提交转账' }), h(NText, {}, { default: () => row.tran.time })] })
            }
            if (row.finish) {
                comps[comps.length] = h(NSpace, {}, { default: () => [h(NText, { type: 'success' }, { default: () => '提现成功' }), h(NText, {}, { default: () => row.finish })] })
            }
            if (row.abort) {
                comps[comps.length] = h(NSpace, {}, { default: () => [h(NText, { type: 'error' }, { default: () => '中止提现' }), h(NText, {}, { default: () => row.abort })] })
            }
            return h(NSpace, { vertical: true }, { default: () => comps })
        },
    },
    {
        title: '说明',
        key: 'memo',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            if (row.tran.state) {
                comps[comps.length] = h(NText, { code: true }, { default: () => row.tran.state })
            } else if (row.handle.time) {
                comps[comps.length] = h(NText, {}, { default: () => row.handle.name })
                comps[comps.length] = h(NText, { code: true }, { default: () => row.handle.memo })
            } else {
                comps[comps.length] = h(NText, { depth: 3 }, { default: () => '暂无说明' })
            }

            return h(NSpace, {}, { default: () => comps })
        },
    },
    {
        title: '操作',
        key: 'actions',
        width: 270,
        align: 'left',
        fixed: 'right',
        render(row: any) {
            let comps: any = []
            comps[comps.length] = h(
                NButton,
                {
                    size: 'small',
                    type: 'info',
                    disabled: row.state != 1,
                    onClick: () => {
                        srows.value = []
                        datas.value = [row]
                        tranActive.value = true
                    },
                },
                { default: () => '转账', icon: () => h(NIcon, {}, { default: () => h(TransactionOutlined, {}, {}) }) }
            )
            comps[comps.length] = h(
                NButton,
                {
                    size: 'small',
                    type: 'success',
                    disabled: row.state != 1 && row.state != 4,
                    onClick: () => {
                        srows.value = []
                        datas.value = [row]
                        finishActive.value = true
                    },
                },
                { default: () => '完成', icon: () => h(NIcon, {}, { default: () => h(CheckCircleOutlineOutlined, {}, {}) }) }
            )
            comps[comps.length] = h(
                NButton,
                {
                    size: 'small',
                    type: 'error',
                    disabled: row.state != 1 && row.state != 4,

                    onClick: () => {
                        srows.value = []
                        datas.value = [row]
                        abortActive.value = true
                    },
                },
                { default: () => '中止', icon: () => h(NIcon, {}, { default: () => h(StopOutlined, {}, {}) }) }
            )

            return h(NSpace, { justify: 'start' }, { default: () => comps })
        },
    },
]

const height = computed(() => store.state.browser.innerHeight - 310)

const srows = ref<string[]>([])

const onCheckRow = (keys: string[]) => {
    srows.value = keys
}

const onChangeSize = (size: number) => {
    param.value.pager.page = 1
    param.value.pager.size = size
    execLoad()
}

const onChangePage = (page: number) => {
    param.value.pager.page = page
    execLoad()
}

const doBatchFinish = () => {
    datas.value = items.value.filter((v: any) => srows.value.includes(v.id))
    finishActive.value = true
}

const doBatchAbort = () => {
    datas.value = items.value.filter((v: any) => srows.value.includes(v.id))
    abortActive.value = true
}

const doBatchTran = () => {
    datas.value = items.value.filter((v: any) => srows.value.includes(v.id))
    tranActive.value = true
}

const dates = ref<number[]>([dayjs().subtract(1, 'month').valueOf(), dayjs().valueOf()])
watch([dates, () => dates.value], (nv, _ov) => {
    let v = nv[0] as number[]
    param.value.query.begin = dayjs(v[0]).format('YYYY-MM-DD')
    param.value.query.close = dayjs(v[1]).format('YYYY-MM-DD')
})

const param = ref({
    query: {
        begin: dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
        close: dayjs().add(1, 'month').format('YYYY-MM-DD'),
        cnl: undefined,
        state: undefined,
        mob: '',
        uid: '',
    },
    pager: {
        page: 1,
        size: 10,
        time: new Date().getTime(),
    },
})

const pager = ref({
    now: 1,
    row: 0,
    all: 0,
    fms: 0,
})
const items = ref([])

const doQuery = () => {
    param.value.pager.page = 1
    execLoad()
}

const execLoad = () => {
    Http.post('/ops/fin/withdraw/list', param.value).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        if (resp.data.pager.now == 1) {
            param.value.pager.time = resp.data.pager.fms
        }
        srows.value = []
        pager.value = resp.data.pager
        items.value = resp.data.items
    })
}

const datas = ref<any[]>([])

const finishActive = ref(false)
const abortActive = ref(false)
const tranActive = ref(false)

const { $dialog: dialog } = window

const doExport = () => {
    Http.post('/ops/fin/withdraw/export', param.value.query).then(resp => {
        if (resp.stat.err > 0) {
            return
        }

        dialog.success({
            title: '导出成功',
            content: `共导出 ${resp.data.count} 条记录，请下载`,
            positiveText: '下载',
            onPositiveClick: () => {
                window.open(resp.data.url, '_blank')
            },
        })
    })
}

onActivated(() => {
    execLoad()
})
</script>
